import { menu, power, login, logout } from "@/api/module/user";
import { generateRoute, generatePower } from "@/route/permission";
import { message } from "ant-design-vue";
import courseExtendRoutes from '@/route/module/course-routes';
import schoolExtendRoutes from '@/route/module/school-routes';
import universityExtendRoutes from '@/route/module/university-routes';
import projectExtendRoutes from '@/route/module/project-routes';
import messageExtendRoute from '@/route/module/message-routes';
import contactExtendRoute from '@/route/module/contact-manage';
import teachingExtendRoute from '@/route/module/teaching-material';
import marketRoutesRoute from '@/route/module/market-routes';
import professorExtendRoutes from '@/route/module/professor-routes';
import courseOutlineExtendRoutes from '@/route/module/course-outline';
import studentrtvExtendRoutes from '@/route/module/student-routes';
import systemExtendRoutes from '@/route/module/system-routers';
// 课程班次价格
import curriculumPrice from '@/route/module/curriculum-price';

/**
 * 添加额外路由
 * @param routes
 * @param path
 * @param extendRoutes
 * @returns {*}
 */
const addExtendRoutes = (routes, path, extendRoutes) => {
  const pathIndex = routes && routes.findIndex(v => v.component === path[0])
  if (pathIndex !== -1) {
    path.shift()
    routes[pathIndex].children = path.length > 0
      ? addExtendRoutes(routes[pathIndex].children, path, extendRoutes)
      : [...routes[pathIndex].children, ...extendRoutes]
  }
  return routes
}

const state = {
  token: '',
  tokenKey: '',
  userInfo: localStorage.getItem('user_info') ? JSON.parse(localStorage.getItem('user_info')) : null,
  userRoutes: [],
  userPowers: [],
  toFromRouter: {
    from: {},
    to: {}
  }
}

const mutations = {
  /// 存储 Token
  SET_USER_TOKEN(state, token) {
    if (token) {
      state.tokenKey = token.key;
      state.token = token.value;
      localStorage.setItem('token_key', token.key)
      localStorage.setItem('token', token.value)
    } else {
      state.tokenKey = '';
      state.token = '';
      localStorage.removeItem('token_key')
      localStorage.removeItem('token')
    }
  },
  /// 存储用户详情
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('user_info', JSON.stringify(userInfo))
  },
  /// 存储用户菜单
  SET_USER_ROUTE(state, menuList) {
    if (menuList && menuList.length === 0) {
      state.userRoutes = []
      localStorage.removeItem('user_routes')
    } else {
      const finalMenu = menuList
      state.userRoutes = finalMenu
      localStorage.setItem('user_routes', JSON.stringify(finalMenu))
    }
  },
  /// 存储用户权限
  SET_USER_POWER(state, powerList) {
    if (powerList && powerList.length === 0) {
      state.userPowers = []
      localStorage.removeItem("user_powers")
    } else {
      const finalPower = powerList;
      state.userPowers = finalPower;
      localStorage.setItem('user_powers', JSON.stringify(finalPower))
    }
  },
  SET_TO_FROM_ROUTER(state, toFromRouter) {
    state.toFromRouter = toFromRouter
  }
}

const actions = {

  // 登录
  async login({ commit }, params) {
    const { code, msg, token, tokenKey, data } = await login(params);
    if (code === 200) {
      commit('SET_USER_INFO', { username: data });
      commit('SET_USER_TOKEN', { key: tokenKey, value: token });
      return Promise.resolve();
    } else {
      return Promise.reject(msg);
    }
  },

  // 注销
  async logout({ commit }) {
    const { msg } = await logout();
    // message.success(msg, 0.5).then(function () {
      commit('SET_USER_TOKEN');
      commit('SET_USER_ROUTE');
      window.location.reload();
    // });
    return Promise.resolve()
  },

  // 路由
  async addRoute({ commit }) {
    const { data } = await menu()
    // 额外的模块,如 添加/修改 路由需在这配置
    addExtendRoutes(
      data, ['university'],
      [
        ...courseExtendRoutes,
        ...schoolExtendRoutes,
        ...universityExtendRoutes,
        ...projectExtendRoutes,
        ...messageExtendRoute,
        ...contactExtendRoute,
        ...marketRoutesRoute,
        ...teachingExtendRoute,
        ...professorExtendRoutes,
        ...courseOutlineExtendRoutes,
        ...curriculumPrice
      ]
    )
    addExtendRoutes(
      data, ['market'],
      [
        ...marketRoutesRoute,
      ]
    )
    addExtendRoutes(
      data, ['system'],
      [
        ...systemExtendRoutes,
      ]
    )
	addExtendRoutes(
		data, ['studentrtv'],
		[
			...studentrtvExtendRoutes,
		]
	)
    commit('SET_USER_ROUTE', generateRoute(data))
  },

  async addPower({ commit }) {
    const { data } = await power()
    commit('SET_USER_POWER', generatePower(data))
  },

  addToFrom({ commit }, route) {
    commit('SET_TO_FROM_ROUTER', route)
  },
}
export default {
  namespaced: true,
  mutations,
  actions,
  state,
}
